package com.icodingedu.springcloud.controller;

import com.icodingedu.springcloud.entity.MessageBean;
import com.icodingedu.springcloud.topic.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public class StreamController {

    @Autowired
    private MyTopic producer;

    @Autowired
    private GroupTopic groupProducer;

    @Autowired
    private DelayedTopic delayedProducer;

    @Autowired
    private ErrorTopic errorPorducer;

    @Autowired
    private RequeueTopic requeueProducer;

    @Autowired
    private DlqTopic dlqProducer;

    @Autowired
    private FallbackTopic fallbackProducer;

    @PostMapping("send")
    public void sendMessage(@RequestParam("body") String body){
        //发送消息给MyTopic通道
        producer.output().send(MessageBuilder.withPayload(body).build());
    }

    @PostMapping("sendgroup")
    public void sendGroupMessage(@RequestParam("body") String body){
        groupProducer.output().send(MessageBuilder.withPayload(body).build());
    }

    @PostMapping("senddm")
    public void sendDmMessage(@RequestParam("body") String body,
                              @RequestParam("second") Integer second){
        MessageBean messageBean = new MessageBean();
        messageBean.setPayload(body);
        log.info("**** 准备进入延迟消息发送 ****");
        delayedProducer.output().send(MessageBuilder.withPayload(messageBean)
                                    .setHeader("x-delay",1000*second)
                                    .build());
    }

    @PostMapping("senderror")
    public void sendErrorMessage(@RequestParam("body") String body){
        errorPorducer.output().send(MessageBuilder.withPayload(body).build());
    }


    @PostMapping("requeue")
    public void sendRQMessage(@RequestParam("body") String body){
        requeueProducer.output().send(MessageBuilder.withPayload(body).build());
    }

    //死信队列
    @PostMapping("dlq")
    public void sendDLQMessage(@RequestParam("body") String body){
        dlqProducer.output().send(MessageBuilder.withPayload(body).build());
    }

    @PostMapping("fallback")
    public void sendFallbackMessage(@RequestParam("body") String body,
                                    @RequestParam(value = "version",defaultValue = "1.0") String version){
        fallbackProducer.output().send(MessageBuilder
                .withPayload(body)
                .setHeader("version",version)
                .build());
    }
}
